import { PopupManager } from "element-ui/lib/utils/popup";
import { handleBodyScroll } from "./utils";

let dialogCount = 0;

export default (Vue, component, propsData = {}, parent, callback) => {
  const container = document.querySelector("#dialog");
  const beforeBodyWidth = document.body.clientWidth;

  const ComponentConstructor = Vue.extend(component);
  let instance = new ComponentConstructor({
    propsData,
    parent,
  }).$mount();
  container.appendChild(instance.$el);

  handleBodyScroll("open", dialogCount, beforeBodyWidth);

  typeof callback === "function" && callback();

  instance.$el.style.zIndex = PopupManager.nextZIndex();

  const destroyDialog = () => {
    if (instance) {
      dialogCount--;
      handleBodyScroll("close", dialogCount);
      instance.$destroy();
      container.removeChild(instance.$el);
      instance = null;
    }
  };

  parent.$once("hook:beforeDestroy", destroyDialog);

  dialogCount++;
  return new Promise((resolve) => {
    instance.$once("close", (...arg) => {
      destroyDialog();
      resolve(...arg);
    });
  });
};
